package leetcode;

public class Code004_IsLand {
    public static int findIslands(int[][] m) {
        if (m == null || m[0] == null) {
            return 0;
        }
        int rows = m.length;
        int cols = m[0].length;
        int res = 0;
        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                if (m[i][j] == 1) {
                    res++;
                    infect(m, i, j, rows, cols);
                }
            }
        }

        return res;
    }

    private static void infect(int[][] m, int i, int j, int rows, int cols) {
        if (i < 0 || i >= rows || j < 0 || j >= cols || m[i][j] != 1) {
            return;
        }
        m[i][j] = 2;
        // 继续感染 上下左右
        infect(m, i - 1, j, rows, cols);
        infect(m, i + 1, j, rows, cols);
        infect(m, i, j - 1, rows, cols);
        infect(m, i, j + 1, rows, cols);

    }

    public static void main(String[] args) {
        int[][] m = {{0,1,0,0,1,0}
                    ,{0,1,1,0,1,0}
                    ,{0,0,1,0,0,0}
                    ,{0,0,0,0,1,0}
                    ,{0,0,0,0,0,0}};
        int a = findIslands(m);
        System.out.println(a);

    }
}
